package br.mec.siep.coletor.endpoint;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

@WebService(
		name="Coletor",
		serviceName = "ColetorService",
		targetNamespace = "http://siep.mec.br/coletor"
)

public class Coletor {
	public Coletor(){
		
	}
	
	@WebMethod(operationName = "receberArquivoB")
	public boolean receberArquivoB(@WebParam(name = "arquivo") 
			DataHandler arquivo, @WebParam(name = "nome") String nome){
		if(arquivo == null){
			return false;
		}
		try{
			File novoArquivo = new File("C:/arquivoServidor/"+nome+"Agora");
			OutputStream out = new FileOutputStream(novoArquivo);
			arquivo.writeTo(out);			
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	
	@WebMethod(operationName = "solicitarColeta")
	public DataHandler solicitarColeta(){		
		try{
			File arquivo = new File("C:/arquivoServidor/dados.txt");
			DataHandler dh = new DataHandler(new FileDataSource(arquivo));
			return dh;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	 public static byte[] fileToByte(File arquivo) throws Exception {
         FileInputStream fis = new FileInputStream(arquivo);
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         byte[] buffer = new byte[8192];
         int bytesRead = 0;
         while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
             baos.write(buffer, 0, bytesRead);
         }
         return baos.toByteArray();
     } 
	
}
